function addItem(obj, lab, key, val, isReadOnly) {
	var typ = 0;
	if (g_date.indexOf(key) != -1) {
		typ = 1;
	} else if (g_gender.indexOf(key) != -1) {
		typ = 2;
	}
	switch (typ) {
	case 0:
		obj.add(new Ext.form.TextField({
			fieldLabel : lab,
			name : key,
			value : val,
			readOnly : isReadOnly
		}));
		break;
	case 1:
		obj.add(new Ext.form.DateField({
			fieldLabel : lab,
			name : key,
			value : val,
			format : 'Y-m-d',
			altFormats : 'Y-m-d',
			readOnly : isReadOnly
		}));
		break;
	case 2:
		obj.add(new Ext.form.ComboBox({
			fieldLabel : lab,
			name : key,
			value : val,
			mode : 'local',
			store : new Ext.data.SimpleStore({
				fields : [ 'value', 'text' ],
				data : [ [ '', '' ], [ '男', '男' ], [ '女', '女' ] ]
			}),
			valueField : 'value',
			displayField : 'text',
			forceSelection : true,
			editable : false,
			triggerAction : 'all',
			readOnly : isReadOnly
		}));
		break;
	}
}
// 初始化整个页面
function init(jsnMetadata) {
	// searchFormPanel's function, separate for enter key.
	function doSearch() {
		if (!searchFormPanel.getForm().isValid()) {
			Ext.example.msg('警告', '校验失败！');
			return;
		}
		ds.baseParams['json'] = Ext.encode(searchFormPanel.getForm()
				.getValues());
		ds.load({
			params : {
				start : 0,
				limit : pagingToolbar.pageSize
			}
		});
	}
	// searchFormPanel
	var searchFormPanel = new Ext.FormPanel({
		region : 'east',
		labelAlign : 'top',
		title : '查询条件',
		split : true,
		// border : false,
		// layout : 'column',
		margins : '5 5 5 0',
		bodyStyle : 'padding-left:5px',
		collapsible : true,
		collapseMode : 'mini',
		frame : true,
		// height : 200,
		width : 200,
		autoScroll : true,
		iconCls : 'icon-search',
		defaults : {
			anchor : '88%'
		},
		buttons : [ {
			text : '查  询',
			handler : doSearch
		}, {
			text : '清  空',
			handler : function() {
				searchFormPanel.getForm().reset();
			}
		} ],
		keys : [ {
			key : Ext.EventObject.ENTER,
			fn : doSearch,
			scope : this
		} ]
	});
	for ( var key in jsnMetadata) {
		if (g_shide.indexOf(key) == -1)
			addItem(searchFormPanel, jsnMetadata[key], key, '', false);
	}
	// gridPanel's components
	var sm = new Ext.grid.CheckboxSelectionModel();
	var arrColumn = [ sm, new Ext.grid.RowNumberer() ];
	var arrField = new Array();
	for ( var key in jsnMetadata) {
		arrColumn.push({
			header : jsnMetadata[key],
			sortable : true,
			dataIndex : key

		});
		arrField.push({
			name : key
		});
	}
	var cm = new Ext.grid.ColumnModel(arrColumn);
	var ds = new Ext.data.Store({
		proxy : new Ext.data.HttpProxy({
			url : 'select.php'
		}),
		reader : new Ext.data.JsonReader({
			totalProperty : 'totalProperty',
			root : 'root',
			fields : arrField
		}),
		baseParams : {
			tname : g_tname
		}
	});

	var insertWindow;
	var insertFormPanel = new Ext.FormPanel({
		labelWidth : 80,
		bodyStyle : 'padding:5px',
		defaults : {
			width : 160
		},
		// width : 275,
		// height : 400,
		autoScroll : true,
		buttons : [
				{
					text : '保  存',
					handler : function() {
						if (!insertFormPanel.getForm().isValid()) {
							Ext.example.msg('警告', '校验失败！');
							return;
						}
						insertFormPanel.getForm().submit(
								{
									waitTitle : '请稍等',
									waitMsg : '保存中...',
									url : 'insert.php',
									success : function(form, action) {
										top.Ext.example.msg('消息', '保存成功！');
										ds.reload();
									},
									failure : function(form, action) {
										Ext.Msg.alert('错误', '保存失败！原因如下：<br>'
												+ action.result.msg);
									},
									params : {
										tname : g_tname
									},
									scope : this
								});
					}

				}, {
					text : '取  消',
					handler : function() {
						insertWindow.hide();
					}
				} ]
	});
	for ( var key in jsnMetadata) {
		addItem(insertFormPanel, jsnMetadata[key], key, '', false);
	}

	var updateWindow;
	var updateFormPanel = new Ext.FormPanel({
		labelWidth : 80,
		bodyStyle : 'padding:5px',
		defaults : {
			width : 160
		},
		// width : 275,
		// height : 400,
		// autoHeight : true,
		autoScroll : true,
		buttons : [
				{
					text : '保  存',
					handler : function() {
						if (!updateFormPanel.getForm().isValid()) {
							Ext.example.msg('警告', '校验失败！');
							return;
						}
						updateFormPanel.getForm().submit(
								{
									waitTitle : '请稍等',
									waitMsg : '保存中...',
									url : 'update.php',
									success : function(form, action) {
										top.Ext.example.msg('消息', '保存成功！');
										ds.reload();
									},
									failure : function(form, action) {
										Ext.Msg.alert('错误', '保存失败！原因如下：<br>'
												+ action.result.msg);
									},
									params : {
										tname : g_tname,
										pkey : g_pkey
									},
									scope : this
								});
					}
				}, {
					text : '取  消',
					handler : function() {
						updateWindow.hide();
					}
				} ]
	});
	for ( var key in jsnMetadata) {
		addItem(updateFormPanel, jsnMetadata[key], key, '',
				g_pkey.indexOf(key) != -1);
	}
	function doInsert() {
		if (!insertWindow) {
			insertWindow = new Ext.Window({
				renderTo : Ext.getBody(),
				layout : 'fit',
				modal : true,
				// IE7对auto支持不好！
				// autoWidth : true,
				// autoHeight : true,
				width : 286,
				height : 400,
				closeAction : 'hide',
				plain : true,
				border : false,
				items : insertFormPanel
			});
		}
		insertFormPanel.getForm().reset();
		insertWindow.show();
	}

	function doUpdate() {
		var record = gridPanel.getSelectionModel().getSelections();
		if (record.length != 1) {
			Ext.Msg.alert('警告', '请选择一项！');
			return;
		}
		if (!updateWindow) {
			updateWindow = new Ext.Window({
				renderTo : Ext.getBody(),
				layout : 'fit',
				modal : true,
				// IE7对auto支持不好！
				// autoWidth : true,
				// autoHeight : true,
				width : 286,
				height : 400,
				closeAction : 'hide',
				plain : true,
				border : false,
				items : updateFormPanel
			});
		}
		// Order is wired! 1.show() 2.setValues()
		// setValues() will work only after FormPanel was rendered.
		// show() can render it, also i use renderTo explicitly.
		// console.log(updateWindow.rendered);
		updateFormPanel.getForm().setValues(record[0].data);
		updateWindow.show();
	}
	// 只把选中项的主键生成json
	function getSelections() {
		var selections = gridPanel.getSelectionModel().getSelections();
		var array = g_pkey.split("|");
		var json = "";
		for ( var i = 0; i < selections.length; i++) {
			json += "{";
			for ( var j = 0; j < array.length; j++) {
				json += "\"" + array[j] + "\":\"" + selections[i].get(array[j])
						+ "\",";
			}
			json = json.substr(0, json.length - 1) + "},";
		}
		json = "[" + json.substr(0, json.length - 1) + "]";
		return json;
	}
	function doDelete(button, event) {
		var json = "";
		if (button.text == '删除选中') {
			var selections = gridPanel.getSelectionModel().getSelections();
			if (selections.length == 0) {
				Ext.Msg.alert('警告', '请至少选择一项！');
				return;
			}
			if (confirm('将删除' + selections.length + '项，是否继续？') != true) {
				return;
			}
			json = getSelections();
		} else if (confirm("将要删除全部，是否继续？") != true) {
			return;
		}
		Ext.Msg.wait('删除中...', "请稍等");
		Ext.Ajax.request({
			url : 'delete.php',
			success : function(response, option) {
				Ext.Msg.hide();
				if (Ext.util.JSON.decode(response.responseText).success) {
					top.Ext.example.msg('消息', '删除成功！');
					ds.reload();
				} else {
					Ext.Msg.alert('错误', '删除失败！原因如下：<br>'
							+ Ext.util.JSON.decode(response.responseText).msg);
				}
			},
			failure : function(response, option) {
				Ext.Msg.hide();
				top.Ext.example.msg('错误', '删除失败！');
			},
			params : {
				tname : g_tname,
				json : json
			}
		});
	}
	function doExport(button, event) {
		var json = "";
		if (button.text == '导出选中') {
			var selections = gridPanel.getSelectionModel().getSelections();
			if (selections.length == 0) {
				Ext.Msg.alert('警告', '请至少选择一项！');
				return;
			}
			json = getSelections();
		}
		window.location.href = 'export.php?tname=' + g_tname + "&json=" + json;
	}
	var pagingToolbar = new Ext.PagingToolbar({
		pageSize : g_page,
		store : ds,
		displayInfo : true
	});
	// gridPanel
	var gridPanel = new Ext.grid.GridPanel({
		region : 'center',
		ds : ds,
		cm : cm,
		sm : sm,
		iconCls : 'icon-grid',
		title : '查询结果',
		enableColumnHide : false, // 导出未实现先隐藏
		frame : true,
		margins : '5 0 5 5',
		viewConfig : {
			forceFit : false
		},
		tbar : [ {
			text : '添加',
			iconCls : 'icon-insert',
			handler : doInsert
		}, '-', {
			text : '修改选中',
			iconCls : 'icon-update',
			handler : doUpdate
		}, '-', {
			text : '删除选中',
			iconCls : 'icon-delete',
			handler : doDelete
		}, '-', {
			text : '删除全部',
			iconCls : 'icon-delete',
			handler : doDelete
		}, '-', new Ext.ux.BrowseButton({
			text : '导入',
			iconCls : 'icon-import',
			url : 'import.php',
			name : 'userfile',
			handler : function() { // 处理成功的fn
				ds.reload();
			},
			scope : this,
			params : {
				tname : g_tname
			}
		}), '-', {
			text : '导出选中',
			iconCls : 'icon-export',
			handler : doExport
		}, '-', {
			text : '导出全部',
			iconCls : 'icon-export',
			handler : doExport
		} ],
		bbar : pagingToolbar
	});

	ds.load({
		params : {
			start : 0,
			limit : g_page
		}
	});

	var viewport = new Ext.Viewport({
		renderTo : Ext.getBody(),
		layout : 'border',
		items : [ searchFormPanel, gridPanel ]
	});

	// 在iframe里关闭top的目录
	Ext.get(document).on("click", function() {
		if (top != self) {
			// top.Ext.example.msg('消息', '触发事件！');
			try {
				top.Ext.menu.MenuMgr.hideAll();
			} catch (e) {
				top.Ext.example.msg('错误', '关闭目录失败！');
			}
		}
	});
}

var g_tname, g_pkey, g_shide, g_date, g_gender, g_page = 20;

Ext.onReady(function() {
	Ext.QuickTips.init();
	// 分离get的参数 并初始化全局变量
	var strGet = window.location.href.split('?')[1];
	if (!strGet) {
		top.Ext.example.msg('错误', '获取get参数失败！');
		return;
	}
	var arrGet = Ext.urlDecode(strGet);

	switch (arrGet['tname']) {
	case "customer":
		g_tname = "customer";
		g_pkey = "tmncode";
		g_shide = "memo1|memo4|bak8";
		g_date = "opendate|repairdate";
		g_gender = "";
		break;
	case "item":
		g_tname = "item";
		g_pkey = "itemunitcode";
		g_shide = "memo1";
		g_date = "";
		g_gender = "";
		break;
	case "input":
		g_tname = "input";
		g_pkey = "itemunitcode";
		g_shide = "amount";
		g_date = "";
		g_gender = "";
		break;
	case "logic":
		g_tname = "logic";
		g_pkey = "tmncode|itemunitcode";
		g_shide = "sale|estimate|minimum";
		g_date = "";
		g_gender = "";
		break;
	case "output":
		g_tname = "output";
		g_pkey = "tmncode|itemunitcode";
		g_shide = "amount";
		g_date = "";
		g_gender = "";
		break;
	case "user":
		g_tname = "user";
		g_pkey = "id";
		g_shide = "password|telephone|email|aboutme";
		g_date = "birthdate";
		g_gender = "gender";
		break;
	case "management":
		g_tname = "management";
		g_pkey = "id|tmncode";
		g_shide = "";
		g_date = "";
		g_gender = "";
		break;
	}
	// 获取元数据
	Ext.getBody().mask('加载中...', 'x-mask-loading');
	Ext.Ajax.request({
		url : 'meta.php',
		success : function(response, option) {
			Ext.getBody().unmask();
			top.Ext.example.msg('消息', '获取元数据成功！')
			// 初始化整个页面;
			init(Ext.util.JSON.decode(response.responseText));
		},
		failure : function(response, option) {
			Ext.getBody().unmask();
			top.Ext.example.msg('错误', '获取元数据失败！');
		},
		params : {
			tname : g_tname
		}
	});

});